<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info"
            show-icon />

        <!-- 表格顶部菜单 -->
        <TableHeader :buttons="['refresh', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: 'ID' + '/' + '分类名称' })" />

        <!-- 表格 -->
        <Table />

        <!-- 表单 -->
        <PopupForm />

        <!-- 详情弹窗 -->
        <OrderInfoForm v-model:visible="baTable.form.infoVisible" :data="baTable.form.data.info" />

    </div>
</template>

<script setup lang="ts">
import { provide, computed } from 'vue'
import baTableClass from '/@/utils/baTable'
import PopupForm from './popupForm.vue'
import OrderInfoForm from './info.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi } from '/@/api/common'
import { useI18n } from 'vue-i18n'
import { fullUrl } from '/@/utils/common'

defineOptions({
    name: 'goods/goodsorder',
})

const timechange = (time: any) => {
    // 空值处理
    if (!time || time === '0000-00-00 00:00:00' || time === '0') {
        return ''
    }

    let date: Date;
    try {
        // 检测是否为10位数字的秒级时间戳
        const timeStr = String(time).trim();
        if (/^\d{10}$/.test(timeStr)) {
            // 10位数字，按秒级时间戳处理，转换为毫秒级
            const timestamp = Number(timeStr) * 1000;
            date = new Date(timestamp);
        } else if (/^\d{13}$/.test(timeStr)) {
            // 13位数字，按毫秒级时间戳处理
            date = new Date(Number(timeStr));
        } else if (time instanceof Date) {
            // Date对象直接使用
            date = time;
        } else {
            // 其他情况尝试直接转换
            date = new Date(time);
        }

        // 检查转换是否成功
        if (isNaN(date.getTime())) {
            return String(time);
        }

        // 格式化日期时间
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');
        const second = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    } catch (error) {
        // 发生错误时返回原始值
        console.warn('时间转换失败:', error);
        return String(time);
    }
}

const { t } = useI18n()
const baTable = new baTableClass(
    new baTableApi('/goodsorder/'),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            {
                label: '订单', prop: 'order', align: 'center', render: 'customTemplate',
                customTemplate: (row) => {
                    return `<div style="text-align: left;">
                                <p>ID: ${row.id}</p>
                                <p>订单号: ${row.order_no}</p>
                                <p>创建时间: ${timechange(row.createtime)}</p>
                                <p>支付时间: ${timechange(row.pay_time)}</p>
                                <p>支付方式: ${row.pay_type || ''}</p>
                                <p>配送类型: ${row.is_self_pickup == 1 ? '上门自提' : '物流配送'}</p>
                            </div>`
                }, width: 220,
            },
            {
                label: '商品', prop: 'goods', align: 'center', render: 'customTemplate', showOverflowTooltip: true, customTemplate: (row) => {
                    if (Array.isArray(row.text)) {
                        return row.text.map(item => `
                            <div style="display: flex; text-align: left; margin-bottom: 10px; height: 100px; border: 1px solid #ebeef5; border-radius: 4px; overflow: hidden;">
                                <!-- 左侧图片 -->
                                <div style="width: 80px; height: 100%; flex-shrink: 0;">
                                    <img src="${fullUrl(item.goods_img || '')}" alt="商品图片" style="width: 100%; height: 100%; object-fit: cover;">
                                </div>
                                <!-- 右侧参数 -->
                                <div style="padding: 8px 12px; flex: 1; display: flex; flex-direction: column; justify-content: space-between;">
                                    <p style="margin: 0; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">${item.goods_name}</p>
                                    <p style="margin: 4px 0 0 0;">x${item.num}</p>
                                    <p style="margin: 4px 0 0 0; color: #f56c6c;">￥${item.price}</p>
                                </div>
                            </div>
                        `).join('');
                    }
                }, width: 250,
            },
            {
                label: '金额(元)', prop: 'total_price', align: 'center', render: 'customTemplate', customTemplate: (row) => {
                    return `<p style="text-align: left;">订单金额:￥${row.total_price}</p>
                            <p style="text-align: left;">会员:${row.discount_price || 0} 积分:${row.score_price || 0} ${Number(row.svip_price) > 0 ? 'SVIP:' + row.svip_price : ''} 优惠券:${row.coupon_price || 0}</p>
                            <p style="text-align: left;">平台手续费:${row.platform_hand_fees}</p>
                            <p style="text-align: left; font-weight: 700;">实付金额:￥${row.pay_price}</p>`
                }, width: 350,
            },
            {
                label: '买家/收货人', prop: 'buyer', align: 'center', render: 'customTemplate', customTemplate: (row) => {
                    return `<div style="text-align: left;">
                                <p>买家: ${row.user_name}</p>
                                <p>手机号: ${row.user_mobile}</p>
                                <p>地址: ${row.user_address}</p>
                            </div>`
                }, width: 250,
            },
            // { label: '订单类型', prop: 'order_type', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
            {
                label: '状态',
                prop: 'status',
                align: 'center',
                render: 'tag',
                custom: {
                    10: 'warning',  // 待支付 - 黄色警告
                    20: 'danger',   // 已取消 - 红色危险
                    30: 'info',     // 待发货 - 蓝色信息
                    31: 'primary',  // 待收货 - 主要蓝色
                    32: 'success',  // 已完成 - 绿色成功
                    33: 'purple',   // 退货退款 - 紫色特殊
                    34: 'orange',   // 退货中 - 橙色提醒
                    35: 'success',  // 售后完成 - 绿色成功
                    40: 'purple',   // 退款中 - 紫色特殊
                    41: 'success',  // 退款完成 - 绿色成功
                    42: 'danger'    // 拒绝退款 - 红色危险
                },
                replaceValue: {
                    10: '待支付',
                    20: '已取消',
                    30: '待发货',
                    31: '待收货',
                    32: '已完成',
                    33: '退货退款',
                    34: '退货中',
                    35: '售后完成',
                    40: '退款中',
                    41: '退款完成',
                    42: '拒绝退款'
                },
            },
            { label: '创建时间', prop: 'createtime', align: 'center', render: 'datetime', sortable: 'custom', operator: 'RANGE', width: 160 },
            {
                label: '操作',
                align: 'center',
                width: '120',
                render: 'buttons',
                buttons: defaultOptButtons(['info', 'edit', 'delete']),
                operator: false,
            },
        ],
        dblClickNotEditColumn: [undefined],
    },
    {
        defaultItems: {
            sort: 0,
            status: 'enable',
            parent_id: 0,
        },
    }
)
// 重写auth方法，绕过权限控制，始终返回true
baTable.auth = function () {
    return true
}

// 初始化详情相关属性
if (!baTable.form.data) {
    baTable.form.data = {}
}
baTable.form.data.info = {}
baTable.form.infoVisible = false

// 详情按钮点击处理
baTable.form.extend!.info = function (row) {
    // 将选中的行数据传递给详情组件
    baTable.form.data.info = row
    baTable.form.infoVisible = true
}

// 详情数据
const infoData = computed(() => baTable.form.data.info || {})

// 状态文本映射
const getStatusText = (status: number) => {
    const statusMap: Record<number, string> = {
        10: '待支付',
        20: '已取消',
        30: '待发货',
        31: '待收货',
        32: '已完成',
        33: '退货退款',
        34: '退货中',
        35: '售后完成',
        40: '退款中',
        41: '退款完成',
        42: '拒绝退款'
    }
    return statusMap[status] || '未知状态'
}

// 处理关闭
const handleClose = () => {
    baTable.form.infoVisible = false
    // 清空数据
    baTable.form.data.info = {}
}

// 处理打印
const handlePrint = () => {
    // 打印逻辑
    console.log('打印订单:', infoData.value.order_no)
    // 这里可以实现实际的打印功能
    alert(`打印订单: ${infoData.value.order_no}`)
}

// 物流查询
const checkExpress = () => {
    console.log('查询物流:', infoData.value.express_name, infoData.value.express_no)
    // 这里可以实现跳转到物流查询页面或打开物流查询弹窗
    alert(`物流公司: ${infoData.value.express_name}\n物流单号: ${infoData.value.express_no}`)
}

// 时间格式化
const formatTime = (time: any) => {
    if (!time || time === '0000-00-00 00:00:00' || time === '0') {
        return ''
    }

    try {
        const timeStr = String(time).trim();
        let date: Date;

        if (/^\d{10}$/.test(timeStr)) {
            date = new Date(Number(timeStr) * 1000);
        } else if (/^\d{13}$/.test(timeStr)) {
            date = new Date(Number(timeStr));
        } else {
            date = new Date(time);
        }

        if (isNaN(date.getTime())) {
            return String(time);
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hour = String(date.getHours()).padStart(2, '0');
        const minute = String(date.getMinutes()).padStart(2, '0');
        const second = String(date.getSeconds()).padStart(2, '0');

        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    } catch (error) {
        return String(time);
    }
}

baTable.mount()
baTable.getData()

provide('baTable', baTable)
</script>

<style scoped lang="scss"></style>
